package leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class l1331_数组序号转换 {

    public static int[] arrayRankTransform(int[] arr) {
        //入参的前置校验
        if (arr == null) {
            return null;
        }

        //阻断式编程
        int[] resultArr = new int[arr.length];
        if (arr.length == 0) {
            return resultArr;
        }

        //备份array数组，原因是array将改变
        int[] helpArr = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            helpArr[i] = arr[i];
        }

        //利用哈希表去存储排好序数组的序号
        Arrays.sort(arr);
        Map<Integer, Integer> arrayIndexHashMap = new HashMap<>();
        int index = 0;
        for (int i = 0; i < arr.length; i++) {
            if (Objects.isNull(arrayIndexHashMap.get(arr[i]))) {
                index++;
                arrayIndexHashMap.put(arr[i], index);
            }
        }

        //得到返回值的结果
        for (int i = 0; i < arr.length; i++) {
            resultArr[i] = arrayIndexHashMap.get(helpArr[i]);
        }

        return resultArr;
    }

}
